package com.taptech.doufu.presenter.novel
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.widget.Toast
import com.taptech.doufu.R
import com.taptech.doufu.bean.HomeTopBean
import com.taptech.doufu.bean.ProductionBean
import com.taptech.doufu.bean.ShareBeansInfo
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.net.retrofit.api.BaseSubscriber
import com.taptech.doufu.model.TupleBean
import com.taptech.doufu.model.novel.NovelDetailsModel
import com.taptech.doufu.model.novel.bean.*
import com.taptech.doufu.presenter.BasePresenter
import com.taptech.doufu.services.personalcenter.AccountService
import com.taptech.doufu.ui.activity.weex.SimpleWeexTransparentActivity
import com.taptech.doufu.ui.dialog.DoubleBtnTiptDialog
import com.taptech.doufu.ui.dialog.SingleBtnDialog
import com.taptech.doufu.weex.TFGiftAnimationUtil
import rx.Observable
import java.util.concurrent.TimeUnit

class NovelDetailsPresenter(context:Activity,view:INovelDetailsView,val intent:Intent) : BasePresenter<INovelDetailsView>(context,view) {

    private val model = NovelDetailsModel(mContext)
    var novelId:Int = intent.getIntExtra(Constant.ID,0)
    private var recommendByNovelBegin = 0
    private var recommendByAuthorBegin = 0
    private var authorId = 0
    private var recommendByAuthorList = mutableListOf<NovelRecommendBean>()
    private var recommendByNovelList = mutableListOf<NovelRecommendBean>()
    private var recommendByAuthorIndex = 0
    private var recommendByNovelIndex = 0
    private var recommendByAuthorHasMore = true
    private var recommendByNovelHasMore = true
    private var collectTimes = 0    //小说收藏数
    var hasAttention = false  //是否关注了该作者
    var hasCollect = false //是否收藏了该小说
    var novelBean = NovelDetailBean()


    fun getNovelDetails() {
        var keyword = ""
        if (intent.hasExtra(Constant.KEYWORD)) {
            keyword = intent.getStringExtra(Constant.KEYWORD) as String
        }
        model.getNovelDetail(novelId,keyword,object : BaseSubscriber<NovelDetailBean>(){
            override fun onNext(t: NovelDetailBean?) {
                super.onNext(t)
                if (t != null) {
                    mView.fillNovelDetail(t)
                    novelBean = t
                    authorId = if (t.user.userId.isNullOrEmpty()) 0 else t.user.userId.toInt()
                    hasAttention = if (t.user.following.isNullOrEmpty()) false else  t.user.following.toInt() != 0
                    hasCollect = t.has_fav
                    collectTimes = if (t.collect_times.isNullOrEmpty()) 0 else t.collect_times.toInt()
                    getNovelShareRank()
                    getRecommendByAuthor()
                    getRecommendByNovel()
                    getBookList()
                }else{
                    mView.showErrorView("数据异常")
                    Toast.makeText(mContext,"数据异常",Toast.LENGTH_LONG).show()
                }
            }

        })
    }

    fun getNovelShareRank(){
        model.getNovelShareRank(novelId,object :BaseSubscriber<NovelShareRankGson>(){
            override fun onNext(t: NovelShareRankGson?) {
                super.onNext(t)
                if (t != null) {
                    mView.fillNovelShareRank(t)
                }
            }
        })
    }


    fun getBookList() {
        model.getNovelBookList(novelId,object :BaseSubscriber<NovelBookListGson>(){
            override fun onNext(t: NovelBookListGson?) {
                super.onNext(t)
                if (t != null) {
                    mView.fillNovelBookList(t.list)
                }
            }
        })
    }

    fun getRecommendByAuthor(){
        if (recommendByAuthorHasMore && recommendByAuthorIndex >= recommendByAuthorList.size-6) {
            model.getRecommendNovel(authorId,0,SIZE,recommendByAuthorBegin,object :BaseSubscriber<NovelRecommendGson>(){
                override fun onNext(t: NovelRecommendGson?) {
                    super.onNext(t)
                    if (t != null) {
                        recommendByAuthorBegin = t.begin
                        if (t.list.size < SIZE) {
                            recommendByAuthorHasMore = false
                        }
                        recommendByAuthorList.addAll(t.list)
                    }
                    setCurrRecommendByAuthorList()
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                    setCurrRecommendByAuthorList()
                }
            })
        }else{
            setCurrRecommendByAuthorList()
        }
    }


    fun getRecommendByNovel() {
        if (recommendByNovelHasMore && recommendByNovelIndex >= recommendByNovelList.size - 6) {
            model.getRecommendNovel(0,novelId,SIZE,recommendByNovelBegin,object :BaseSubscriber<NovelRecommendGson>(){
                override fun onNext(t: NovelRecommendGson?) {
                    super.onNext(t)
                    if (t != null) {
                        recommendByNovelBegin =  t.begin
                        if (t.list.size < SIZE) {
                            recommendByNovelHasMore = false
                        }
                        recommendByNovelList.addAll(t.list)
                    }
                    setCurrRecommendByNovelList()
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                    setCurrRecommendByNovelList()
                }
            })
        }else{
            setCurrRecommendByNovelList()
        }
    }


    private fun setCurrRecommendByAuthorList() {
        val curList = mutableListOf<NovelRecommendBean>()
        if (recommendByAuthorList.size <= 4) {
            when {
                recommendByAuthorList.size == 1 -> curList.add(recommendByAuthorList[0])
                recommendByAuthorList.size == 2 -> {
                    curList.add(recommendByAuthorList[0])
                    curList.add(recommendByAuthorList[1])
                }
                recommendByAuthorList.size == 3 -> {
                    curList.add(recommendByAuthorList[0])
                    curList.add(recommendByAuthorList[1])
                    curList.add(recommendByAuthorList[2])
                }
                recommendByAuthorList.size == 4 -> {
                    curList.add(recommendByAuthorList[0])
                    curList.add(recommendByAuthorList[1])
                    curList.add(recommendByAuthorList[2])
                    curList.add(recommendByAuthorList[3])
                }
            }
            mView.fillRecommendByAuthor(curList,false)
        }else{
            if (recommendByAuthorIndex < recommendByAuthorList.size - 1) {
                recommendByAuthorIndex += 1
            }else{
                recommendByAuthorIndex = 0
            }
            curList.add(recommendByAuthorList[recommendByAuthorIndex])
            if (recommendByAuthorIndex < recommendByAuthorList.size - 1) {
                recommendByAuthorIndex += 1
            }else{
                recommendByAuthorIndex = 0
            }
            curList.add(recommendByAuthorList[recommendByAuthorIndex])
            if (recommendByAuthorIndex < recommendByAuthorList.size - 1) {
                recommendByAuthorIndex += 1
            }else{
                recommendByAuthorIndex = 0
            }
            curList.add(recommendByAuthorList[recommendByAuthorIndex])
            if (recommendByAuthorIndex < recommendByAuthorList.size - 1) {
                recommendByAuthorIndex += 1
            }else{
                recommendByAuthorIndex = 0
            }
            curList.add(recommendByAuthorList[recommendByAuthorIndex])
            mView.fillRecommendByAuthor(curList,true)
        }
    }

    private fun setCurrRecommendByNovelList() {
        val curList = mutableListOf<NovelRecommendBean>()
        if (recommendByNovelList.size <= 4) {
            when {
                recommendByNovelList.size == 1 -> curList.add(recommendByNovelList[0])
                recommendByNovelList.size == 2 -> {
                    curList.add(recommendByNovelList[0])
                    curList.add(recommendByNovelList[1])
                }
                recommendByNovelList.size == 3 -> {
                    curList.add(recommendByNovelList[0])
                    curList.add(recommendByNovelList[1])
                    curList.add(recommendByNovelList[2])
                }

                recommendByNovelList.size == 4 -> {
                    curList.add(recommendByNovelList[0])
                    curList.add(recommendByNovelList[1])
                    curList.add(recommendByNovelList[2])
                    curList.add(recommendByNovelList[3])
                }
            }
            mView.fillRecommendByNovel(curList,false)
        }else{
            if (recommendByNovelIndex < recommendByNovelList.size - 1) {
                recommendByNovelIndex += 1
            }else{
                recommendByNovelIndex = 0
            }
            curList.add(recommendByNovelList[recommendByNovelIndex])
            if (recommendByNovelIndex < recommendByNovelList.size - 1) {
                recommendByNovelIndex += 1
            }else{
                recommendByNovelIndex = 0
            }
            curList.add(recommendByNovelList[recommendByNovelIndex])
            if (recommendByNovelIndex < recommendByNovelList.size - 1) {
                recommendByNovelIndex += 1
            }else{
                recommendByNovelIndex = 0
            }
            curList.add(recommendByNovelList[recommendByNovelIndex])
            if (recommendByNovelIndex < recommendByNovelList.size - 1) {
                recommendByNovelIndex += 1
            }else{
                recommendByNovelIndex = 0
            }
            curList.add(recommendByNovelList[recommendByNovelIndex])
            mView.fillRecommendByNovel(curList,true)
        }
    }

    fun attentionUser() {
        if (hasAttention) {
            model.cancelAttentionUser(authorId,object : BaseSubscriber<Boolean>(){

                override fun onNext(t: Boolean?) {
                    super.onNext(t)
                    if (t!=null && t) {
                        hasAttention = false
                        mView.attentionUser(true, success = true)
                    }else{
                        mView.attentionUser(true, success = false)
                    }
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                    mView.attentionUser(true, success = false)
                }

            })
        }else{
            model.attentionUser(authorId,object : BaseSubscriber<NovelAttentionBean>(){
                override fun onNext(t: NovelAttentionBean?) {
                    super.onNext(t)
                    if (t != null) {
                        hasAttention = true
                        mView.attentionUser(false, success = true)
                    }else{
                        mView.attentionUser(false, success = false)
                    }
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                    mView.attentionUser(false, success = false)
                }
            })
        }
    }

    fun praiseComment(id:Int,position:Int,cancel:Boolean/*是否取消赞*/){
        if (cancel) {
            model.cancelPraiseComment(id,object : BaseSubscriber<Boolean>(){
                override fun onNext(t: Boolean?) {
                    super.onNext(t)
                    if (t != null && t) {
                        mView.praiseComment(position,cancel,success = true)
                    }else{
                        mView.praiseComment(position,cancel,success = false)
                    }
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                    mView.praiseComment(position,cancel,success = true)
                }
            })
        }else{
            model.praiseComment(id,object :BaseSubscriber<Boolean>(){
                override fun onNext(t: Boolean?) {
                    super.onNext(t)
                    if (t != null && t) {
                        mView.praiseComment(position,cancel,success = true)
                    }else{
                        mView.praiseComment(position,cancel,success = false)
                    }
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                    mView.praiseComment(position,cancel,success = true)
                }

            })
        }
    }


    fun collectNovel(){
        val uid  = AccountService.getInstance().userUid
        if (hasCollect){  //取消收藏
            model.cancelCollectNovel(uid.toInt(),novelBean.object_type,novelId,object : BaseSubscriber<Boolean>(){
                override fun onNext(t: Boolean?) {
                    super.onNext(t)
                    if (t != null && t) {
                        collectTimes -=1
                        hasCollect = false
                        mView.collectNovel(false,collectTimes)
                    }else{
                        mView.collectNovel(true,collectTimes)
                    }
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                    mView.collectNovel(true,collectTimes)
                }
            })
        }else{  //收藏
            model.collectNovel(uid.toInt(),novelBean.object_type,novelId,object :BaseSubscriber<Boolean>(){
                override fun onNext(t: Boolean?) {
                    super.onNext(t)
                    if (t != null && t) {
                        collectTimes += 1
                        hasCollect = true
                        mView.collectNovel(true,collectTimes)
                    }else{
                        mView.collectNovel(false,collectTimes)
                    }
                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                    mView.collectNovel(false,collectTimes)
                }
            })
        }
    }

    fun buyFullBook(){
        model.getNovelChapterList(novelId,object :BaseSubscriber<TupleBean<Float,Boolean>>(){
            override fun onNext(t: TupleBean<Float, Boolean>?) {
                super.onNext(t)
                if (t != null) {
                    var endPrice = if (novelBean.full_activity.activity_price>0) novelBean.full_activity.activity_price else novelBean.end_price
                    if (t.obj1 != -1f){
                        if (t.obj1 == 0f || novelBean.is_full_paid){
                            val dialog = SingleBtnDialog(mContext, R.style.updateDialog,"您已经购买过该完本了,无需再次购买","提示","确定")
                            dialog.setOnBtnClickListener {
                                mView.buyFullBook()
                            }
                            dialog.show()
                        }else if(t.obj1 < endPrice && t.obj2){
                            val tip = "由于您曾订阅该小说部分章节，剩余章节总价低于${endPrice}豆币完本价，您可以${t.obj1}豆币购买该完本"
                            val spannableString = SpannableStringBuilder()
                            spannableString.append(tip)
                            val index = tip.indexOf("${t.obj1}")
                            val span = ForegroundColorSpan(Color.parseColor("#fe6e6e"))
                            spannableString.setSpan(span, index, index+"$endPrice".length, Spannable.SPAN_PRIORITY)
                            val dialog = DoubleBtnTiptDialog(mContext,R.style.updateDialog,
                                    spannableString,"购买", DoubleBtnTiptDialog.CallBack {
                                buyChapter()
                            })
                            dialog.show()
                        }else{
                            val tip = "您将使用${endPrice}豆币购买《${novelBean.title}》全本"
                            val spannableString = SpannableStringBuilder()
                            spannableString.append(tip)
                            val index = tip.indexOf("$endPrice")
                            val span = ForegroundColorSpan(Color.parseColor("#fe6e6e"))
                            spannableString.setSpan(span, index, index+"$endPrice".length, Spannable.SPAN_PRIORITY)
                            val dialog = DoubleBtnTiptDialog(mContext,R.style.updateDialog,
                                    spannableString,"购买", DoubleBtnTiptDialog.CallBack {
                                buyTheBook()
                            })
                            dialog.show()
                        }
                    }
                }
            }
        })
    }

    private fun buyTheBook() {

        TFGiftAnimationUtil.loading(mContext, "http://weex.doufu.la/images/novel_icon/gmz@2x_2.png")
        model.buyTheBook(novelId,18,object :BaseSubscriber<NovelBuyBean>(){
            override fun onNext(t: NovelBuyBean?) {
                super.onNext(t)
                if (t!=null && t.success) {
                    TFGiftAnimationUtil.close("购买成功", true)
                    mView.buyFullBook()
                    if (!t.message.isNullOrEmpty()) {
                        Observable.timer(4,TimeUnit.SECONDS)
                                .subscribe {
                                    val map = hashMapOf<String, Any>()
                                    map["info"] = t.message
                                    map["redArr"] = t.redArr
                                    map["url"] = t.noticeUrl
                                    SimpleWeexTransparentActivity.startActivity(mContext,"TFNovel/freeAlert.js?present=1", map)
                                }
                    }
                }else{
                    if (t != null && !t.user_msg.isNullOrEmpty()) {
                        Toast.makeText(mContext,t.user_msg,Toast.LENGTH_LONG).show()
                    }else{
                        Toast.makeText(mContext,"购买失败",Toast.LENGTH_LONG).show()
                    }
                    TFGiftAnimationUtil.close("购买失败", false)
                }
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
                Toast.makeText(mContext,"购买失败",Toast.LENGTH_LONG).show()
                TFGiftAnimationUtil.close("购买失败", false)
            }
        })
    }

    private fun buyChapter() {
        TFGiftAnimationUtil.loading(mContext, "http://weex.doufu.la/images/novel_icon/gmz@2x_2.png")
        model.buyAllChapter(novelId,18,object :BaseSubscriber<NovelBuyBean>(){
            override fun onNext(t: NovelBuyBean?) {
                super.onNext(t)
                if (t!=null && t.result) {
                    mView.buyFullBook()
                    TFGiftAnimationUtil.close("购买成功", true)
                }else{
                    if (t != null && !t.user_msg.isNullOrEmpty()) {
                        Toast.makeText(mContext,t.user_msg,Toast.LENGTH_LONG).show()
                    }else{
                        Toast.makeText(mContext,"购买失败",Toast.LENGTH_LONG).show()
                    }
                    TFGiftAnimationUtil.close("购买失败", false)
                }
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
                Toast.makeText(mContext,"购买失败",Toast.LENGTH_LONG).show()
                TFGiftAnimationUtil.close("购买失败", false)
            }
        })
    }


    fun getProductionBean():ProductionBean{
        val bean = HomeTopBean()
        bean.id = novelId.toString()
        if (novelBean.object_type > 0) {
            bean.object_type = "${novelBean.object_type}"
        }else{
            bean.object_type = "18"
        }
        bean.user = novelBean.user
        return bean
    }


    fun getShareBean(): ShareBeansInfo {
        val shareBean = ShareBeansInfo()
        shareBean.id = "$novelId"
        shareBean.dataType = 1
        if (novelBean.recommend_text.isNullOrEmpty()) {
            shareBean.shartText = novelBean.des
        }else{
            shareBean.shartText = novelBean.recommend_text
        }
        shareBean.imagUrl = novelBean.with_image_w
        shareBean.title = novelBean.title
        shareBean.shareUrl = novelBean.shareUrl
        shareBean.object_type = "${novelBean.object_type}"
        return shareBean
    }

    companion object {
        const val SIZE = 15
    }


}